package com.example.zhongshuishi.service.implService;

import com.alibaba.fastjson.JSON;
import com.example.zhongshuishi.entity.PaymentNotifyDTO;
import com.example.zhongshuishi.entity.PaymentOrder;
import com.example.zhongshuishi.entity.StudentDto;
import com.example.zhongshuishi.mapper.PaymentOrderMapper;
import com.example.zhongshuishi.mapper.StudentMapper;
import com.example.zhongshuishi.service.PaymentService;
import com.example.zhongshuishi.utils.OurpayKit;
import com.example.zhongshuishi.utils.QRCodeUtil;
import com.github.pagehelper.PageHelper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private PaymentOrderMapper paymentOrderMapper;
    @Autowired
    private StudentMapper studentMapper;

    private static final String MCH_NO = "E259974018811";
    private static final String APP_ID = "6806008be4b077e7ee68e255";
    private static final String MD5_KEY = "r7yu2j8f1bjtv9d57c47y8bpobwsfj6g8ywktyvkilj40uxjgxarrocvbue2lg4d6wciropth06c8k35pywtn085v7umo0f0qnk63m92c0z0xheqlncy73z1ofrxchwi";
    private static final String PAYMENT_URL = "https://tp.allinpay.com/pay/api/pay/unifiedOrder";
    private static final String APPLET_URL = "https://tp.allinpay.com/applet/getAppletUrl"; // 新增小程序链接生成接口地址
  //  public static final String priRsaKey ="MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDNCH60TTVuLrDaj0FezKvIN23jYIiWH0Fp6RGmdGSVF5i+ASA+hxVb35g887QXVrCy2/61EoDBwgm3XwGO9yxXBIhMH8yahBvcgnJ+kIwPV+3MTvKReTPX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PeQlUkrhnTsWDOvUy87DOC6EUCgYEAii4aq2thiLc0joafDYNJioLK6FMj4EmerAt6RMfT+IASYqkVN7d/DlF9gTSYJBH5IQfLPKMQVNfKK2HSEAkBIT+UfgPbVaDbgm/RvLuQnywxcFJd7ko5oPMmT3NhxPrlEK3zG37M8X8wEn0vnO3dgzJpCGLy0JsQs6B0tSGkhokCgYEA0aJHS85KhPf/QOyAuxxZ2EyJHYQw8bDZt24htuvXre2McDL8CATcv72rxrRub7OeL5fvsnIVKP9UVj4N2ahzTh4gyQWivK14hgbq0DhIgmlPnX2PG1YoWqo7O4Qzi2mUv0AoehntmeZGIT4sBH06RWBHvx/6lvcH3bjY54lemUk=";

    @Override
    public boolean processPaymentNotify(PaymentNotifyDTO notifyDTO) {
        StudentDto order = studentMapper.selectByOrderNo(notifyDTO.getMchOrderNo());
        if (order == null) {
            return false;
        }

//        if (!order.getPayment().equals(String.valueOf(notifyDTO.getAmount()))) {
//            return false;
//        }

        String paymentStatus = notifyDTO.getState() == 2 ? "1" : "0";
        order.setPaymentStatus(paymentStatus);
        order.setTransactionId(notifyDTO.getPayOrderId());
        order.setPayChannel(notifyDTO.getIfCode());
        order.setPaymentTime(String.valueOf(new Date(notifyDTO.getSuccessTime())));

        int result = studentMapper.updatePaymentStatusByOrderNo(notifyDTO.getMchOrderNo(), paymentStatus);
        return result > 0;
    }

    @Override
    public String createPayment(StudentDto student, String paymentMethod) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("mchNo", MCH_NO);
        params.put("appId", APP_ID);
        params.put("reqTime", String.valueOf(System.currentTimeMillis()));
        params.put("version", "1.0");
        params.put("signType", "RSA");
        params.put("mchOrderNo", student.getOrderNo());
        params.put("wayCode", paymentMethod);
        params.put("amount", "229800"); // 固定支付金额为2298元，单位为分
        params.put("currency", "cny");
        params.put("body", "学生报名费用");
        params.put("notifyUrl", "http://9k3390539z.zicp.fun/student/pay/callback");
       //params.put("notifyUrl", "http://47.95.176.90:8080/student/pay/callback");

        String sign = OurpayKit.getSign(params);
        params.put("sign", sign);
        String response = doPostJson(PAYMENT_URL, JSON.toJSONString(params));

        JSONObject jsonResponse = new JSONObject(response);
        String code = jsonResponse.optString("code", "UNKNOWN");
        if ("0".equals(code)) { // 支付成功
            if (!jsonResponse.has("data") || !(jsonResponse.get("data") instanceof JSONObject)) {
                throw new RuntimeException("响应数据中缺少有效的 'data' 字段");
            }

            JSONObject data = jsonResponse.getJSONObject("data");
            if (!data.has("payData")) {
                throw new RuntimeException("响应数据中缺少 'payData' 字段");
            }

            String payData = data.getString("payData");
            String qrCodeBase64 = extractQRCodeFromPayData(payData);
            return qrCodeBase64; // 返回二维码信息
        } else {
            String msg = jsonResponse.optString("msg", "未知错误");
            throw new RuntimeException("支付失败: " + msg);
        }
    }

    @Override
    public String getAppletUrl(StudentDto student) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("mchNo", MCH_NO);
        params.put("appId", APP_ID);
        params.put("reqTime", String.valueOf(System.currentTimeMillis()));
        params.put("version", "1.0");
        params.put("signType", "RSA"); // 使用 RSA 签名类型
        params.put("mchOrderNo", student.getOrderNo());
        params.put("wayCode", "ALI_QR");
        params.put("amount", "229800"); // 固定支付金额为2298元，单位为分
        params.put("currency", "cny");
        params.put("notifyUrl", "www...");

        params.put("body", "学生报名费用");

        String sign = OurpayKit.getSign(params);
        params.put("sign", sign);

        String response = doPostJson(APPLET_URL, JSON.toJSONString(params));
        return parseAppletResponse(response);
    }

    /**
     * 新增方法：生成订单号并返回二维码信息
     */
    public String generateOrderAndQRCode(StudentDto student) throws Exception {
        String response = getAppletUrl(student);

        JSONObject jsonResponse = new JSONObject(response);
        if (!jsonResponse.has("data") || !(jsonResponse.get("data") instanceof JSONObject)) {
            throw new RuntimeException("响应数据中缺少有效的 'data' 字段");
        }

        JSONObject data = jsonResponse.getJSONObject("data");
        if (!data.has("payData")) {
            throw new RuntimeException("响应数据中缺少 'payData' 字段");
        }

        String payData = data.getString("payData");
        return extractQRCodeFromPayData(payData);
    }


    private String extractQRCodeFromPayData(String payData) {


            // 使用 QRCodeUtil 生成二维码图片
            int width = 200; // 二维码宽度
            int height = 200; // 二维码高度
            return QRCodeUtil.generateQRCode(payData, width, height);

    }


        public static String doPostJson(String url, String json) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            try {
                HttpPost httpPost = new HttpPost(url);
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return resultString;
        }


        private String parsePaymentResponse(String response) {
            try {
                JSONObject json = new JSONObject(response);
                String code = json.optString("code", "UNKNOWN");
                if ("SUCCESS".equals(code)) {
                    return "SUCCESS";
                } else {
                    String msg = json.optString("msg", "未知错误");
                    throw new RuntimeException("支付失败: " + msg);
                }
            } catch (JSONException e) {
                throw new RuntimeException("解析支付响应失败: " + e.getMessage(), e);
            }
        }

    private String parseAppletResponse(String response) {
        try {
            if (response == null || response.isEmpty()) {
                throw new RuntimeException("响应为空，无法解析");
            }

            JSONObject json;
            try {
                json = new JSONObject(response);
            } catch (JSONException e) {
                throw new RuntimeException("JSON 格式错误，无法解析响应: " + response, e);
            }

            if (json == null || !json.has("code")) {
                throw new RuntimeException("JSON 格式错误，缺少 'code' 字段");
            }

            String code = json.optString("code", "unknown");
            if ("0".equals(code)) {
                if (!json.has("data") || !(json.get("data") instanceof JSONObject)) {
                    throw new RuntimeException("JSON 格式错误，缺少有效的 'data' 字段");
                }

                JSONObject data = json.getJSONObject("data");
                return data.getString("appletUrl");
            } else {
                String msg = json.optString("msg", "未知错误");
                throw new RuntimeException("获取小程序链接失败: " + msg);
            }
        } catch (JSONException e) {
            // 捕获 JSON 解析异常并抛出自定义异常
            throw new RuntimeException("JSON 解析失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Map<String, Object> queryPaymentOrder(String orderId) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("mchNo", MCH_NO);
        params.put("appId", APP_ID);
        params.put("reqTime", String.valueOf(System.currentTimeMillis()));
        params.put("version", "1.0");
        params.put("signType", "RSA");
        params.put("mchOrderNo", orderId);

        String sign = OurpayKit.getSign(params);
        params.put("sign", sign);

        String response = doPostJson("https://tp.allinpay.com/pay/api/pay/query", JSON.toJSONString(params));

        // 解析响应结果
        JSONObject jsonResponse = new JSONObject(response);
        String code = jsonResponse.optString("code", "UNKNOWN");
        if ("0".equals(code)) { // 查询成功
            if (!jsonResponse.has("data") || !(jsonResponse.get("data") instanceof JSONObject)) {
                throw new RuntimeException("响应数据中缺少有效的 'data' 字段");
            }

            JSONObject data = jsonResponse.getJSONObject("data");
            int state = data.getInt("state");

            if (state == 2) {
                studentMapper.updatePaymentStatusByOrderNo(orderId, "1");
            }

            if (state == 1) {
                Map<String, Object> result = new HashMap<>();
                result.put("status", "UNPAID");
                result.put("message", "订单未支付");
                return result;
            }

            return jsonResponse.toMap();
        } else {
            String msg = jsonResponse.optString("msg", "未知错误");
            throw new RuntimeException("查询失败: " + msg);
        }
    }

    @Override
    public List<PaymentOrder> selectByIdOrderNo(String stuId,String orderNo,Integer currPage,Integer pageSize) {
        if(currPage != null || pageSize != null){
            PageHelper.startPage(currPage, pageSize);
        }
        return paymentOrderMapper.selectByIdOrderNo(stuId,orderNo);
    }

}
